import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Dimensions,
} from 'react-native';

import styles from '../../order/editOrderStyle';
import CustomListView from '../../global/CustomListView';
import ToastTip from '../../global/ToastTip';
import ListViewActivityIndicator from '../../global/ListViewActivityIndicator';
import api from 'services/api';
import _ from 'lodash';
import Communications from 'react-native-communications';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class NormalList extends Component {
    constructor(props) {
		super(props);
        let {approveStatus=0} = props;
		this.state = {
			currentPage: 1,
            noData: false,
            totalCount: 0,
            approveStatus,
            dataList: []
		};

        this.totalpage = 0;
        this.pagesize = 20;
        this.list = [];

	}

    componentDidMount() {
        this._mounted = true;
        this.onLoad();
    }

    onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {
        this._mounted = false;
        this.timeIndex && clearTimeout(this.timeIndex);
    }

    _onSearchResultListItemPress(rowData){
        // this.props.parent.setState({addressFirst: `${rowData.first_address}${rowData.second_address}`});
    }

    async _getWithdrawList(){
        let {approveStatus} = this.state;
        this.setState({ currentPage: 1 });
        let list = await api.post('/delivery/getDeliveryRecordListGJ', {
                    approveStatus,
                    page:1,
                    pagesize: this.pagesize
                });
        if(list.cd == 1){
            this.refs.toast.show(list.msg);
            this._withdrawByList._pullToRefreshListView.endRefresh(false);
            return;
        }

       if(Platform.OS == 'ios') {
           this._endWithdrawList(list.data);
       } else {
           this.timeIndex = setTimeout(() => {
               this._endWithdrawList(list.data);
           }, 200);
       }
    }

    _endWithdrawList(list){
        this.totalpage = list.total_page;
        this.list = list.res;

        if(!this._mounted){
            return;
        }

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        this._withdrawByList.setState({
            dataList: list.res,
            dataSource: this._withdrawByList._dataSource.cloneWithRows(list.res)
        });

        this.setState({totalCount: list.count, dataList: list.res});

        this._activityIndicator.setState({ visible: false,});
        this._withdrawByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
		if (this.state.currentPage !== this.totalpage) {

			let page;
            page = this.state.currentPage + 1;
            this.setState({ currentPage: page });

            let list;
            list = await api.post('/delivery/getDeliveryRecordListGJ', {
                           approveStatus:this.state.approveStatus,
                           page:page,
                           pagesize: this.pagesize
                        });

            if(list.cd == 1){
                this.refs.toast.show(list.msg);
                this._withdrawByList._pullToRefreshListView.endRefresh(false);
                return;
            }

           const newData = list.data.res;
           newData.map((item, index) => this.list.push(item));

           this._withdrawByList.setState({
               dataList: this.list,
               dataSource: this._withdrawByList._dataSource.cloneWithRows(this.list),
           });
           this._withdrawByList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._withdrawByList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }

    _firePhone(phone){
        Communications.phonecall(phone, true);
    }

    homeAddress(data){
        let address ='';
        if(data.homeNeighbourhoods){
            address += data.homeNeighbourhoods
        }
        if(data.homeBuilding){
            address += data.homeBuilding
        }
        if(data.homeUnit){
            address += data.homeUnit
        }
        if(data.roomNo){
            address += data.roomNo
        }
        return address;
    }

    //跳转详情页面
    _toDetail(id){
        let {navigator} = this.props;
        navigator.push({
            title: "资料详情",
            backButtonTitle:'',
            screen: 'housekeeperapp.deliverydetail',
            passProps: {
                id
            },
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarNoBorder: true,
                navBarTextColor: 'white',
                navBarButtonColor: 'white',
                navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                topBarElevationShadowEnabled:false,
                navBarTitleTextCentered: true
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("img/hk_back_icon.png")
                    }
                ]
            }
            // backButtonHidden: true,
        });
    }

    //未审核 以及审核通过
    _renderRow(rowData, sectionID, rowID){
        return (
            <TouchableOpacity activeOpacity={0.8} onPress={this._toDetail.bind(this, rowData.ownerId)} style={{backgroundColor:'#fff',}}>
                <View
                    style={{
                        marginLeft:15,
                        paddingTop:15,
                        paddingBottom:15,
                        flexDirection: 'row',
                        alignItems:'center',
                        borderBottomWidth: StyleSheet.hairlineWidth,
                        borderColor: "#DEDEDE",

                    }}
                >
                    <View
                        style={{
                            borderRightWidth: StyleSheet.hairlineWidth,
                            borderColor: "#DEDEDE",
                            flex:1
                        }}
                    >
                        <View
                            style={{flexDirection: 'row',alignItems:'flex-end'}}
                        >
                            <Text style={{paddingRight:10,fontSize: 18, color: '#555555',}}>{rowData.ownerName}</Text>
                            <Text style={{fontSize:13, color: '#7B7B7B',marginLeft:5}}>{rowData.applyTime}</Text>
                        </View>
                        <Text style={{fontSize: 15, color: '#7B7B7B', marginTop: 6, }}>{this.homeAddress(rowData)}</Text>
                    </View>
                    <TouchableOpacity onPress={this._firePhone.bind(this, rowData.ownerPhone)} style={{justifyContent: 'flex-end',marginRight:22,marginLeft:22}}>
                        <Image source={require('../../../../img/hk_phone_icon.png')}/>
                    </TouchableOpacity>
                </View>
            </TouchableOpacity>
        );
    }

    //审核驳回
    _renderRejectRow(rowData, sectionID, rowID){
        return (
            <View
                style={{
                    marginBottom:10,
                    backgroundColor:'#fff',
                    borderBottomWidth:StyleSheet.hairlineWidth,
                    borderTopWidth:StyleSheet.hairlineWidth,
                    borderColor: "#DEDEDE",
                }}
            >
                {this._renderRow(rowData, sectionID, rowID)}
                <View
                    style={{
                        marginLeft:15,
                        paddingRight:15,
                        paddingTop:10,
                        paddingBottom:10,
                        flexDirection:'row',
                    }}
                >
                    <Text style={{fontSize:15,color:"#565656"}}>驳回原因：</Text>
                    <Text
                        style={{
                            flex:1,
                            fontSize:15,
                            textAlign:'justify',
                            color:"#565656"
                        }}
                    >{rowData.rejectReason||'无'}</Text>
                </View>
            </View>
        )
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无记录</Text>
            </View>
        );
    }

    renderHeader(status){
        let name = {
            0:'未审核',
            1:'审核通过',
            2:'审核驳回'
        }
        // if(status == 1){
        //     return (
        //         <View style={{paddingTop:10,paddingBottom:10,borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
        //             <Text style={{fontSize: 15, color: '#7B7B7B',textAlign:'center'}}>
        //                 审核通过：{this.state.totalCount}人
        //             </Text>
        //         </View>
        //     )
        // }
        // if(status == 2){
        //     return (
        //         <View style={{paddingTop:10,paddingBottom:10,borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
        //             <Text style={{fontSize: 15, color: '#7B7B7B',textAlign:'center'}}>
        //                 审核驳回：{this.state.totalCount}人
        //             </Text>
        //         </View>
        //     )
        // }
        return (
            <View style={{paddingTop:10,paddingBottom:10,borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                <Text style={{fontSize: 15, color: '#7B7B7B',textAlign:'center'}}>
                    {name[status]}：{this.state.totalCount}人
                </Text>
            </View>
        )
    }

    render() {
        let {approveStatus} = this.state;
        let renderRow = null,contentStyle ={}
        if(approveStatus==2){
            renderRow = this._renderRejectRow.bind(this);
            contentStyle.backgroundColor = '#f3f3f3'
        }else{
            renderRow = this._renderRow.bind(this);
        }
        return (
            this.state.noData?this._renderNodata():
            <View style={{flex: 1, backgroundColor: '#f3f3f3',}}>
                {this.renderHeader(approveStatus)}
                <CustomListView
                    contentStyle={{backgroundColor:"#f3f3f3"}}
                    dataList={this.state.dataList}
                    ref={ (component) => this._withdrawByList = component }
                    onRefresh={this._onRefresh.bind(this)}
                    onLoadMore={this._onLoadMore.bind(this)}
                    renderRow ={renderRow}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
                <ToastTip ref="toast" offsetY={160}/>
            </View>
        );
    }
}

var connectHelper = require('../../../services/connectHelper');
NormalList = connectHelper(state => state)(NormalList);

module.exports = NormalList;
